package com.sxj.corejava.code13_JDBC;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Test10_事务操作 {

    public static void main(String[] args) throws DataAccessException, SQLException {
        User user = new User("test2", "123456", "13612345698", "江苏-南京");
        insertUser(user);
    }

    public static void insertUser(User user) throws DataAccessException, SQLException {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtil.getConnection();
            // 开启事务,即将MySQL的事务从自动事务改为手动事务
            conn.setAutoCommit(false);
            String sql = new StringBuffer()
                    .append(" insert into ")
                    .append(" t_user ")
                    .append("   (username,password,phone,address) ")
                    .append(" values")
                    .append("   (?,?,?,?)")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1, user.getUsername());
            ps.setString(2, user.getPassword());
            ps.setString(3, user.getPhone());
            ps.setString(4, user.getAddress());
            int row = ps.executeUpdate();
            System.out.println("Query OK, " + row + " row affected");

            int i = 1 / 0;
            // 提交事务
            conn.commit();
        } catch (DataAccessException e) {
            e.printStackTrace();
            // 回滚事务
            conn.rollback();
            throw e;
        } catch (SQLException e) {
            e.printStackTrace();
            // 回滚事务
            conn.rollback();
            throw new DataAccessException(e);
        } finally {
            JDBCUtil.close(conn, ps, rs);
        }
    }

}
